//
//  HBLogic.m
//  MyApplication
//
//  Created by 彭凯敏 on 15/7/30.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "HBLogic.h"
#import "SecrityLogic.h"
#import "Hb.pb.h"
//#import "MainCmd.pb.h"


#import "NetEngine.h"
#define HBTIME  60

@implementation HBLogic
{
    NSTimer *connectTimer;//心跳包计时器
    
}


static HBLogic* _instance = nil;

+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[HBLogic alloc] init] ;
    });
    
    return _instance ;
}

-(id)init {
    connectTimer = [NSTimer scheduledTimerWithTimeInterval:HBTIME target:self selector:@selector(sendHB) userInfo:nil repeats:YES];
    return self;
}


- (void)sendHB
{
    if ([[UserLogic shareInstance] getUserId]) {
        KeepAliveBuilder *builder = [[KeepAliveBuilder alloc]init];
        [builder setTs:[[KMGetDate nowTimeSp] intValue]];
        [self sendRequest:CMD_CONN_HB PBMsg:builder.build];
    }
}

#pragma mark - RequestDelegate

- (void)onResult:(Packet *)result req:(Request *)req
{
    if (result.ret == 0) {
        NSData *plain =[[SecrityLogic shareInstance] decryptSession:result.eBody];
        
        if([CMD_CONN_HB isEqualToString:result.cmd])
        {
            KeepAlive *aliveResp = [KeepAlive parseFromData:plain];
            DLog(@"keepAlive.timeStamp = %@",[KMGetDate timeFromNum:[NSString stringWithFormat:@"%llu",aliveResp.ts]]);
        }
    } else {
        DLog(@"heartbeat fail");
        [[NetEngine shareInstance]heartbeatFail];
    }
    
}

@end
